package util

import (
	"bytes"
	"crypto/md5"
	"encoding/hex"
	"io"
	"os"
	"path/filepath"
)

func MD5(data []byte) string {
	hash := md5.New()
	io.Copy(hash, bytes.NewReader(data))
	key := hex.EncodeToString(hash.Sum(nil))
	return key
}

// 清空目录中的所有文件
func ClearDir(dir string) error {
	d, err := os.Open(dir)
	if err != nil {
		return err
	}
	defer d.Close()

	names, err := d.Readdirnames(-1)
	if err != nil {
		return err
	}

	for _, name := range names {
		err = os.RemoveAll(filepath.Join(dir, name))
		if err != nil {
			return err
		}
	}
	return nil
}
